package comment

import (
	"context"
	"enjoy-shop/formdata"
	client "gitee.com/enjoy_5/comment-rpc/client/comment"
	"gitee.com/enjoy_5/comment-rpc/proto/comment"
	userclient "gitee.com/enjoy_5/user-rpc/client"
	"gitee.com/enjoy_5/user-rpc/proto/user"
	"strconv"
)

func AddComment(data *formdata.AddComment) (*comment.CreateCommentResp, error) {
	return client.CreateComment(context.Background(), &comment.CreateCommentReq{Comment: &comment.CommentInfo{
		ObjectId:   data.ObjectId,
		UserId:     data.UserId,
		File:       data.File,
		Rating:     data.Rating,
		Text:       data.Text,
		Pid:        data.Pid,
		ObjectType: comment.TYPE(data.ObjectType),
	}})
}

func DelComment(data *formdata.DelComment) (*comment.DelCommentResp, error) {
	return client.DelComment(context.Background(), &comment.DelCommentReq{CommentId: data.Id})
}

func GetComment(data *formdata.GetCommentList) (c []*formdata.CommentList, err error) {
	list, err := client.GetCommentList(context.Background(), &comment.GetListReq{
		Page:       data.Page,
		Size:       data.Size,
		Order:      comment.ORDER(data.Order),
		Rating:     comment.RATING(data.Rating),
		ObjectId:   data.ObjectId,
		ObjectType: comment.TYPE(data.ObjectType),
	})
	if err != nil {
		return nil, err
	}
	var userId []int64
	for _, v := range list.Comment {
		userId = append(userId, v.UserId)
	}
	u, err := userclient.UserList(context.Background(), &user.UserListRequest{Userid: userId})
	if err != nil {
		return nil, err
	}
	// 构建用户ID到用户数据的映射
	userMap := make(map[int64]*user.UserInfo)
	for _, userData := range u.UserData {
		uid, err := strconv.ParseInt(userData.Id, 10, 64)
		if err != nil {
			continue
		}
		userMap[uid] = userData
	}

	for _, v := range list.Comment {
		var (
			userName string
			userImg  string
		)

		if userData, exists := userMap[v.UserId]; exists {
			userName = userData.UserName
			userImg = userData.Img
		}

		c = append(c, &formdata.CommentList{
			Id:         v.Id,
			ObjectId:   v.ObjectId,
			UserId:     v.UserId,
			File:       v.File,
			Rating:     v.Rating,
			Text:       v.Text,
			Pid:        v.Pid,
			ObjectType: int64(v.ObjectType),
			CreateTime: v.CreateTime,
			Like:       v.Like,
			UserName:   userName, // 直接填充用户名
			UserImg:    userImg,  // 直接填充用户头像
		})
	}
	return
}

func GetCommentNumByRating(data *formdata.GetCNumByRat) (*comment.GetCNumByRatResp, error) {
	var Rating []comment.RATING
	for _, v := range data.Rating {
		Rating = append(Rating, comment.RATING(v))
	}
	return client.GetCNumByRat(context.Background(), &comment.GetCNumByRatReq{
		Rating: Rating,
	})
}

func LikeComment(data *formdata.CommentLike) (*comment.UpdateLikeResp, error) {
	like := comment.UpdateLike{
		CommentId: data.CommentId,
		UserId:    data.UserId,
	}
	return client.LikeComment(context.Background(), &comment.UpdateLikeReq{Like: &like})
}
